﻿using System.Linq;
using HtmlAgilityPack;
using System.Web.Script.Serialization;
using OneBlog.DataAccessLayer;
using OneBlog.Model.Entities;
using OneBlog.Model.Enum;
using System.Collections.Generic;
using System;

namespace OneBlog.BusinessLogicLayer
{
    public class DataHelper
    {
        private HtmlWeb _htmlWeb = new HtmlWeb();
        /// <summary>
        /// 根据用户导入cnblog数据
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public string Import(string userName)
        {
            int blosNumber = 0;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string url = "http://www.cnblogs.com/" + userName + @"/mvc/blog/sidecolumn.aspx";
            HtmlWeb htmlweb = new HtmlWeb();
            var docment = htmlweb.Load(url);
            string userid = GetCnblogUserId(userName);
            var liS = docment.DocumentNode.SelectNodes("//*[@id='sidebar_categories']/div[1]/ul/li");
            foreach (var item in liS)
            {
                var tXPath = item.XPath;
                var href = item.SelectSingleNode(tXPath + "/a").Attributes["href"].Value;
                var blogtype = htmlweb.Load(href);
                //var entrylistItem = blogtype.DocumentNode.SelectNodes("//*[@id='mainContent']/div/div[2]/div[@class='entrylistItem']");
                var entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='entrylistItem']");
                if (null == entrylistItem)//做兼容
                    entrylistItem = blogtype.DocumentNode.SelectNodes("//div[@class='post post-list-item']"); //    
                if (null == entrylistItem)
                {
                    continue;
                }
                foreach (var typeitem in entrylistItem)
                {
                    var typeitemXPath = typeitem.XPath;
                    var typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/div/a");
                    if (null == typeitemhrefObj) //做兼容
                        typeitemhrefObj = typeitem.SelectSingleNode(typeitemXPath + "/h2/a");
                    var typeitemhref = typeitemhrefObj.Attributes["href"].Value;
                    if (IsAreBlog(typeitemhref))
                        continue;//说明这篇文章已经备份过了的
                    var bloghtml = htmlweb.Load(typeitemhref);
                    var blogcontextobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cnblogs_post_body']");//.InnerHtml;
                    if (blogcontextobj == null) continue;//有可能是加密文章
                    var blogcontext = blogcontextobj.InnerHtml;
                    var blogtitle = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").InnerText;
                    var blogurl = bloghtml.DocumentNode.SelectSingleNode("//*[@id='cb_post_title_url']").Attributes["href"].Value;
                    var blogtypetagurl = "http://www.cnblogs.com/mvc/blog/CategoriesTags.aspx?blogApp=" + userName + "&blogId=" + userid + "    =" +
                        typeitemhref.Substring(typeitemhref.LastIndexOf('/') + 1, typeitemhref.LastIndexOf('.') - typeitemhref.LastIndexOf('/') - 1);
                    //var blogtag = Blogs.Common.Helper.MyHtmlHelper.GetRequest(blogtypetagurl);
                    //var jsonobj = jss.Deserialize<Dictionary<string, string>>(blogtag);
                    //if (null == jsonobj)
                    //    continue;//如果没有 则返回  (这里只能去 数字.html  不能取那种自定义的url)
                    //var tagSplit = jsonobj["Tags"].Split(',');
                    //var blogtagid = new List<int>();
                    //for (int i = 0; i < tagSplit.Length; i++)
                    //{
                    //    if (tagSplit[i].Length >= 1 && tagSplit[i].LastIndexOf('<') >= 1)
                    //    {
                    //        var blogtagname = tagSplit[i].Substring(tagSplit[i].IndexOf('>') + 1, tagSplit[i].LastIndexOf('<') - tagSplit[i].IndexOf('>') - 1);
                    //        blogtagid.Add(this.GetTagId(blogtagname, userName));
                    //    }
                    //}
                    //var categoriesSplit = jsonobj["Categories"].Split(',');
                    //var blogtypeid = new List<int>();
                    //for (int i = 0; i < categoriesSplit.Length; i++)
                    //{
                    //    if (categoriesSplit[i].Length >= 1 && categoriesSplit[i].LastIndexOf('<') >= 1)
                    //    {
                    //        var blogtypename = categoriesSplit[i].Substring(categoriesSplit[i].IndexOf('>') + 1, categoriesSplit[i].LastIndexOf('<') - categoriesSplit[i].IndexOf('>') - 1);
                    //        blogtypeid.Add(this.GetTypeId(blogtypename, userName));
                    //    }
                    //}
                    //var blogtimeobj = bloghtml.DocumentNode.SelectSingleNode("//*[@id='post-date']");
                    //var blogtime = "";
                    //if (null != blogtimeobj)
                    //    blogtime = blogtimeobj.InnerText;


                    //BlogsBLL blog = new BlogsBLL();
                    //var myBlogTags = new BlogTagsBLL().GetList(t => blogtagid.Contains(t.Id), isAsNoTracking: false).ToList();//.ToList();                                        

                    //var myBlogTypes = new BLL.BlogTypesBLL().GetList(t => blogtypeid.Contains(t.Id), isAsNoTracking: false).ToList();//.ToList();
                    //try
                    //{
                    //    var modelMyBlogs = new ModelDB.Blogs()
                    //    {
                    //        BlogContent = blogcontext,
                    //        BlogCreateTime = blogtime,
                    //        BlogTitle = blogtitle,
                    //        BlogUrl = blogurl,
                    //        IsDel = false,
                    //        BlogTags = myBlogTags,
                    //        BlogTypes = myBlogTypes,
                    //        UsersId = GetUserId(userName),
                    //        BlogForUrl = blogurl,
                    //        IsForwarding = iszf == "checked"
                    //    };
                    //    blog.Add(modelMyBlogs);
                    //    blog.save();
                    //    blosNumber++;
                    //}
                    //catch (Exception)
                    //{
                    //    throw;
                    //}
                }
            }
            if (blosNumber > 0)
                return "成功导入" + blosNumber + "篇Blog";
            return "ok";
        }

        /// <summary>
        /// 获取haojima用户id
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private int GetUserId(string userName)
        {
            using (var context = new BlogDbContext())
            {
                var user = context.BlogUsers.FirstOrDefault(u => u.UserName == userName);
                if (user != null)
                    return user.Id;
                else
                {
                    var newUser = context.BlogUsers.Add(new BlogUser()
                    {
                        UserName = userName,
                        Password = "admin",
                        NickName = userName
                    });
                    context.SaveChanges();
                    return newUser.Id;

                }
            }
        }

        private int GetTagId(string tagname, string userName)
        {
            using (var context = new BlogDbContext())
            {
                var tag = context.BlogTypes.Where(t => t.Name == tagname && t.CreateUser.UserName == userName && t.Type == BlogTypes.Tag).Select(t => t.Id).ToList();
                if (tag.Count() > 0)
                {
                    return tag[0];
                }
                else
                {
                    var newTag = context.BlogTypes.Add(new BlogType()
                    {
                        Name = tagname,
                        UserId = GetUserId(userName),
                        Type = BlogTypes.Tag
                    });
                    return newTag.Id;
                }
            }
        }


        private int GetTypeId(string typename, string userName)
        {
            using (var context = new BlogDbContext())
            {
                var tag = context.BlogTypes.Where(t => t.Name == typename && t.CreateUser.UserName == userName && t.Type == BlogTypes.Category).Select(t => t.Id).ToList();
                if (tag.Count() > 0)
                {
                    return tag[0];
                }
                else
                {
                    var newTag = context.BlogTypes.Add(new BlogType()
                    {
                        Name = typename,
                        UserId = GetUserId(userName),
                        Type = BlogTypes.Category
                    });
                    return newTag.Id;
                }
            }
        }



        /// <summary>
        /// 检查 这个 url地址 是否被添加过
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool IsAreBlog(string url)
        {
            using (var context = new BlogDbContext())
            {
                return context.BlogInfoes.Where(b => b.Url == url).Count() >= 1;
            }
        }

        /// <summary>
        /// 获取cnblog用户id
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string GetCnblogUserId(string url)
        {
            HtmlWeb htmlweb = new HtmlWeb();
            var docment = htmlweb.Load("http://www.cnblogs.com/" + url);
            var list = docment.DocumentNode.SelectNodes("//link[@rel='stylesheet']");
            foreach (var item in list)
            {
                if (null != item.Attributes && item.Attributes.Contains("href"))
                {
                    var href = item.Attributes["href"].Value;
                    href = href.Substring(href.LastIndexOf("/") + 1, href.IndexOf(".") - href.LastIndexOf("/") - 1);
                    int userid = -1;
                    if (int.TryParse(href, out userid))
                        return userid.ToString();
                }
            }
            return "";
        }

        /// <summary>
        /// 用户同步
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public BlogUser ImportBlogUser(string userName)
        {
            using (var context = new BlogDbContext())
            {
                var user = context.BlogUsers.FirstOrDefault(u => u.UserName == userName);
                if (user != null)
                    return user;
                else
                {
                    var document = _htmlWeb.Load($"http://www.cnblogs.com/mvc/blog/news.aspx?blogApp={userName}");
                    var nickName = document.DocumentNode.SelectSingleNode("//a[1]").InnerText;
                    var newUser = context.BlogUsers.Add(new BlogUser()
                    {
                        UserName = userName,
                        Password = "admin",
                        NickName = nickName,
                        Email = "93498174@qq.com"
                    });
                    context.SaveChanges();
                    return newUser;

                }
            }
        }

        public int ImportBlogInfo(string userName)
        {
            HtmlDocument document = null;
            HtmlNodeCollection blogInfoes = null;
            do
            {
                document = _htmlWeb.Load($"http://www.cnblogs.com/{userName}/");
                var tempBlogInfoes =
                    document.DocumentNode.SelectNodes("//div[@id='mainContent']//div[@class='postTitle']/a[1]");
                foreach (var tempBlogInfo in tempBlogInfoes)
                {
                    blogInfoes.Add(tempBlogInfo);
                }
            } while (true);

            //新思路  
            //判断是否存在下一页 不存在 直接更新  存在  则跳到下一页 获取所有分页链接 再 导入



            return 1;
        }
    }
}